package tools.event;

import java.util.HashMap;
import java.util.Map;

public class Events {

    private final static Map<String, Observer<?>> observers = new HashMap<>();

    @SuppressWarnings("unchecked")
    public static <T> void addListener(Class<T> event, Listener<T> listener) {
        Observer<T> eventObserver = (Observer<T>) observers.get(event.getName());
        if (eventObserver == null) {
            eventObserver = new Observer<>();
            observers.put(event.getName(), eventObserver);
        }

        eventObserver.addListener(listener);
    }

    @SuppressWarnings("unchecked")
    public static <T> void setPersistence(Class<T> event, Persistence<T> persistence) {
        Observer<T> eventObserver = (Observer<T>) observers.get(event.getName());
        if (eventObserver == null) {
            eventObserver = new Observer<>();
            observers.put(event.getName(), eventObserver);
        }

        eventObserver.setPersistence(persistence);
    }

    @SuppressWarnings("unchecked")
    public static <T> boolean push(T target) {
        if (target == null) {
            return false;
        }

        Observer<T> observer = (Observer<T>) observers.get(target.getClass().getName());

        if (observer == null) {
            return false;
        }

        return observer.observe(target);
    }

}
